package org.budo.phone.rongying;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.budo.phone.api.AbstractPhoneEvent;
import org.budo.phone.api.AbstractPhoneEventFilter;
import org.budo.phone.api.BudoPhoneEventListener;
import org.budo.support.lang.util.StringUtil;
import org.budo.support.mvcs.Mvcs;
import org.budo.support.servlet.util.ResponseUtil;
import org.budo.time.Time;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Slf4j
@Getter
@Setter
public class BudoRongyingPhoneEventFilter extends AbstractPhoneEventFilter {
    private BudoPhoneEventListener budoPhoneEventListener;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // {Host=qqz820006d8.ngrok.wendal.cn, Content-Length=147, X-Forwarded-For=47.96.248.68, User-Agent=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727), Content-Type=application/json;charset=UTF-8, Accept=application/json}
        // [{"Key":"FromPhone","Value":"13699466308"},{"Key":"ToPhone","Value":"80446100000004"},{"Key":"callSid","Value":"190403151415901100010214000bbb2f"}]

        String requestBody = Mvcs.getRequestBody(request);
        if (StringUtil.isEmpty(requestBody)) {
            log.warn("#36 requestBody=" + requestBody + ", headerMap=" + Mvcs.getRequestHeaderMap(request) + ", request=" + request + ", this=" + this);
            super.doFilter(request, response, chain);
            return;
        }

        AbstractPhoneEvent event = new AbstractPhoneEvent();
        // event.setRequestBody(requestBody);

        this.getBudoPhoneEventListener().onEvent(event);

        ResponseUtil.writeToResponse(response, "BudoRongyingPhoneEventFilter-" + Time.now().toString("yyyyMMdd.HHmmss.SSS"));
    }
}